from pathlib import Path

from fastapi import APIRouter, Request, File, UploadFile
from fastapi import Depends
from config.get_db import get_db
from module_admin.entity.vo.cms_home_vo import HomeStatsSum
from module_admin.dao.dept_dao import *
from module_admin.service.login_service import get_current_user_details
from utils.response_util import *
from utils.log_util import *
from utils.uuid import UUID
from config.config import Config


dataController = APIRouter(dependencies=[Depends(get_current_user_details)])

UPLOAD_FOLDER = "./static"

Path(UPLOAD_FOLDER).mkdir(parents=True, exist_ok=True)


@dataController.post("/upload", summary="上传")
async def upload(request: Request, file: UploadFile = File(...), query_db: Session = Depends(get_db)):
    try:
        split = file.filename.split(".")
        txt = split[len(split) - 1]
        file.filename = "data_" + UUID().uuid() + "." + txt
        filepath = Path(UPLOAD_FOLDER) / file.filename
        with open(filepath, "wb+") as buffer:
            contents = await file.read()
            buffer.write(contents)
        return response_200(data={"fileName": "http://vms-dev.cytechs.cn/api/static/" + file.filename}, message="上传成功")
    except Exception as e:
        logger.exception(e)
        return response_500(data="", message=str(e))


@dataController.get("/get/{filename}", summary="获取")
async def get(request: Request, filename: str, query_db: Session = Depends(get_db)):
    try:
        split = filename.split("/")
        filename = split[len(split) - 1]
        filepath = Path(UPLOAD_FOLDER) / filename
        if not filepath.exists() or not filepath.is_file():
            return response_500(data=None, message="没有该文件")
        return StreamingResponse(filepath.open("rb"), media_type="application/octet-stream",
                                 headers={"Content-Disposition": f"attachment; filename={filename}"})
    except Exception as e:
        logger.exception(e)
        return response_500(data="", message=str(e))


